package com.example.sakurasay.passwordbook.viewmodels

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.example.sakurasay.passwordbook.data.PasswordBookDatabase
import com.example.sakurasay.passwordbook.data.PasswordBookRepository
import com.example.sakurasay.passwordbook.data.entities.IndependentPasswordEntry
import com.example.sakurasay.security.EncryptionManager
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

class IndependentPasswordViewModel(application: Application) : AndroidViewModel(application) {

    private val repository: PasswordBookRepository
    val allEntries: Flow<List<IndependentPasswordEntry>>

    init {
        val database = PasswordBookDatabase.getDatabase(application)
        val independentPasswordDao = database.independentPasswordDao()
        val sharedPasswordDao = database.sharedPasswordDao()
        val encryptionManager = EncryptionManager(application)
        repository = PasswordBookRepository(independentPasswordDao, sharedPasswordDao, encryptionManager)
        allEntries = repository.allIndependentPasswords
    }

    fun insert(entry: IndependentPasswordEntry) = viewModelScope.launch {
        repository.insertIndependentPassword(entry)
    }

    fun update(entry: IndependentPasswordEntry) = viewModelScope.launch {
        repository.updateIndependentPassword(entry)
    }

    fun delete(entry: IndependentPasswordEntry) = viewModelScope.launch {
        repository.deleteIndependentPassword(entry)
    }
}